class LiteratureApp {
    constructor() {
        this.allArticles = []; // 保存所有文件列表
        this.articles = []; // 当前显示的文章列表
        this.keywords = {};
        this.selectedKeywords = new Set();
        this.hiddenArticles = new Set(); // 隐藏的文章索引
        this.selectedArticle = null;
        
        this.initializeEventListeners();
    }

    initializeEventListeners() {
        // 加载数据按钮
        document.getElementById('load-data-btn').addEventListener('click', () => {
            this.loadData();
        });

        // 排序选择
        document.getElementById('sort-select').addEventListener('change', (e) => {
            this.sortArticles();
        });

        // 排序顺序选择
        document.getElementById('sort-order-select').addEventListener('change', (e) => {
            this.sortArticles();
        });
    }

    async loadData() {
        // 创建文件输入元素
        const fileInput = document.createElement('input');
        fileInput.type = 'file';
        fileInput.accept = '.json,.pkl,.pickle';
        
        return new Promise((resolve) => {
            fileInput.onchange = async (event) => {
                const file = event.target.files[0];
                if (!file) {
                    resolve();
                    return;
                }
                
                // 只返回文件名
                const fileName = file.name;
                
                try {
                    // 加载文件
                    const loadResponse = await fetch('/api/load_file', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ file_path: fileName })
                    });
                    const loadResult = await loadResponse.json();
                    
                    if (!loadResult.success) {
                        alert('加载文件失败: ' + loadResult.error);
                        resolve();
                        return;
                    }

                    // 保存所有文件列表
                    this.allArticles = loadResult.all_articles || [];
                    
                    // 更新前端页面
                    this.updateFromInfo(loadResult.info);
                    resolve();
                } catch (error) {
                    console.error('加载数据失败:', error);
                    alert('加载数据失败: ' + error.message);
                    resolve();
                }
            };
            
            // 触发文件选择对话框
            fileInput.click();
        });
    }

    // 根据后端返回的info字段更新前端页面
    updateFromInfo(info) {
        if (!info) return;
        
        // 更新关键词树（从kw_graph字段，现在是叶子节点列表）
        if (info.kw_graph) {
            // 将叶子节点列表转换为树形结构
            this.keywords = this.buildTreeFromLeaves(info.kw_graph);
            this.renderKeywordTree();
        }
        
        // 更新选中的关键词（从selected_kw字段）
        if (info.selected_kw) {
            this.selectedKeywords = new Set(info.selected_kw);
            this.renderSelectedKeywords();
        }
        
        // 更新隐藏的文章索引（从hidden_idx字段）
        if (info.hidden_idx) {
            this.hiddenArticles = new Set(info.hidden_idx);
        }
        
        // 更新当前显示的文章列表（从selected_idx字段）
        if (info.selected_idx) {
            this.articles = info.selected_idx.map(index => [index, this.allArticles[index]]);
            this.renderArticleList();
            this.updateArticleCount();
        }
    }

    // 将叶子节点列表转换为树形结构
    buildTreeFromLeaves(leaves) {
        const tree = {};
        
        for (const leaf of leaves) {
            const parts = leaf.split('/');
            let current = tree;
            
            for (let i = 0; i < parts.length; i++) {
                const part = parts[i];
                if (!current[part]) {
                    current[part] = {};
                }
                current = current[part];
            }
        }
        
        return tree;
    }

    async selectKeyword(keyword) {
        try {
            const response = await fetch('/api/select_keywords', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ keywords: keyword })
            });
            
            const result = await response.json();
            if (result.success) {
                // 更新前端页面
                this.updateFromInfo(result.info);
            }
        } catch (error) {
            console.error('选择关键词失败:', error);
        }
    }

    async deselectKeyword(keyword) {
        try {
            const response = await fetch('/api/deselect_keywords', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ keywords: keyword })
            });
            
            const result = await response.json();
            if (result.success) {
                // 更新前端页面
                this.updateFromInfo(result.info);
            }
        } catch (error) {
            console.error('取消选择关键词失败:', error);
        }
    }

    async sortArticles() {
        try {
            const sortBy = document.getElementById('sort-select').value;
            const reverse = document.getElementById('sort-order-select').value === 'true';
            
            if (!sortBy) return; // 如果没有选择排序字段，则不执行排序
            
            const response = await fetch('/api/sort_by', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ 
                    sort_by: sortBy,
                    reverse: reverse 
                })
            });
            
            const result = await response.json();
            if (result.success) {
                // 更新前端页面
                this.updateFromInfo(result.info);
            }
        } catch (error) {
            console.error('排序失败:', error);
        }
    }

    async hideArticle(articleIndex) {
        try {
            const response = await fetch('/api/hide_article', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ article_index: articleIndex })
            });
            
            const result = await response.json();
            if (result.success) {
                // 如果隐藏的是当前选中的文章，清空详情页
                if (this.selectedArticle && this.selectedArticle.index === articleIndex) {
                    this.selectedArticle = null;
                    this.hideArticleDetail();
                }
                // 更新前端页面
                this.updateFromInfo(result.info);
            }
        } catch (error) {
            console.error('隐藏文章失败:', error);
        }
    }

    showArticleDetail(articleIndex) {
        // 前端实现文章详细信息显示
        if (articleIndex >= 0 && articleIndex < this.allArticles.length) {
            const article = this.allArticles[articleIndex];
            this.selectedArticle = {
                index: articleIndex,
                date: article.date,
                title: article.title,
                author: article.author,
                score: article.score || 'N/A',
                publication: article.publication || 'N/A',
                abstract: article.abstract || '',
                keywords: article.keywords || [],
                note: article.note || ''
            };
            this.renderArticleDetail();
        }
    }

    renderArticleList() {
        const container = document.getElementById('article-items');
        
        if (!this.articles || this.articles.length === 0) {
            container.innerHTML = '<div class="loading">暂无文章数据</div>';
            return;
        }

        container.innerHTML = this.articles.map(([index, article]) => `
            <div class="article-item ${this.selectedArticle && this.selectedArticle.index === index ? 'selected' : ''}" 
                 onclick="app.selectArticle(${index})">
                <div class="article-title">${this.escapeHtml(article.title)}</div>
                <div class="article-meta">
                    <span class="article-author">${this.escapeHtml(article.author)}</span>
                    <span class="article-date">${article.date}</span>
                    <span class="article-score">${article.score}</span>
                </div>
                <div class="article-keywords">
                    ${article.keywords.slice(0, 3).map(keyword => 
                        `<span class="keyword-tag">${this.escapeHtml(keyword)}</span>`
                    ).join('')}
                    ${article.keywords.length > 3 ? '<span class="keyword-tag">...</span>' : ''}
                </div>
            </div>
        `).join('');
    }

    renderKeywordTree() {
        const container = document.getElementById('keyword-tree');
        
        if (!this.keywords || Object.keys(this.keywords).length === 0) {
            container.innerHTML = '<div class="loading">暂无关键词数据</div>';
            return;
        }

        container.innerHTML = this.renderKeywordNode(this.keywords, '');
    }

    renderKeywordNode(node, prefix) {
        let html = '';
        
        for (const [key, value] of Object.entries(node)) {
            const fullPath = prefix ? `${prefix}/${key}` : key;
            const isSelected = this.selectedKeywords.has(fullPath);
            const hasChildren = Object.keys(value).length > 0;
            
            // 显示当前节点名称（不是完整路径）
            const displayName = key;
            
            html += `
                <div class="keyword-item ${isSelected ? 'selected' : ''}" 
                     onclick="app.toggleKeywordSelection('${fullPath}')">
                    <span class="keyword-text">${this.escapeHtml(displayName)}</span>
                </div>
            `;
            
            if (hasChildren) {
                html += `<div class="keyword-children">${this.renderKeywordNode(value, fullPath)}</div>`;
            }
        }
        
        return html;
    }

    renderSelectedKeywords() {
        const container = document.getElementById('selected-keywords');
        
        if (this.selectedKeywords.size === 0) {
            container.innerHTML = '<div class="loading">未选择关键词</div>';
            return;
        }

        container.innerHTML = Array.from(this.selectedKeywords).map(keyword => `
            <span class="selected-keyword" onclick="app.deselectKeyword('${keyword}')">
                ${this.escapeHtml(keyword)}
                <span class="remove-btn">×</span>
            </span>
        `).join('');
    }

    renderArticleDetail() {
        const container = document.getElementById('article-detail-content');
        
        if (!this.selectedArticle) {
            container.innerHTML = '<div class="no-selection">请选择一篇文章查看详情</div>';
            return;
        }

        const article = this.selectedArticle;
        container.innerHTML = `
            <div class="detail-header">
                <div class="detail-title">${this.escapeHtml(article.title)}</div>
                <div class="detail-meta">
                    <div><strong>作者:</strong> ${this.escapeHtml(article.author)}</div>
                    <div><strong>日期:</strong> ${article.date}</div>
                    <div><strong>评分:</strong> ${article.score}</div>
                    <div><strong>发表刊物:</strong> ${this.escapeHtml(article.publication)}</div>
                </div>
            </div>
            
            <div class="detail-section">
                <h4>摘要</h4>
                <div class="detail-abstract">${this.escapeHtml(article.abstract)}</div>
            </div>
            
            <div class="detail-section">
                <h4>关键词</h4>
                <div class="detail-keywords">
                    ${article.keywords.map(keyword => 
                        `<span class="detail-keyword">${this.escapeHtml(keyword)}</span>`
                    ).join('')}
                </div>
            </div>
            
            ${article.note ? `
                <div class="detail-section">
                    <h4>备注</h4>
                    <div class="detail-abstract">${this.escapeHtml(article.note)}</div>
                </div>
            ` : ''}
            
            <div class="detail-actions">
                <button class="btn btn-danger" onclick="app.hideArticle(${article.index})">
                    隐藏文章
                </button>
            </div>
        `;
    }

    hideArticleDetail() {
        const container = document.getElementById('article-detail-content');
        container.innerHTML = '<div class="no-selection">请选择一篇文章查看详情</div>';
    }

    selectArticle(index) {
        // 显示文章详情
        this.showArticleDetail(index);
        // 更新文章列表中的选中状态
        this.renderArticleList();
    }

    async toggleKeywordSelection(keyword) {
        if (this.selectedKeywords.has(keyword)) {
            await this.deselectKeyword(keyword);
        } else {
            await this.selectKeyword(keyword);
        }
    }

    updateArticleCount() {
        const countElement = document.getElementById('article-count');
        countElement.textContent = this.articles.length;
    }

    escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }
}

// 初始化应用
let app;
document.addEventListener('DOMContentLoaded', () => {
    app = new LiteratureApp();
    // 页面加载完成后可以手动加载数据
    console.log('文献管理应用已初始化，点击"加载数据"按钮开始使用');
});